﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_DSJCJ.Common;
using System.Data;
using System.Text.RegularExpressions;
using ElingOA6_DSJCJ.Models;
using Newtonsoft.Json;
using Webdiyer.WebControls.Mvc;

namespace ElingOA6_DSJCJ.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class SubOfficeController : Controller
    {
        //
        // GET: /SubOffice/
        private ElingOA6_DSJCJ.BLL.DocCls docClsBLL = new ElingOA6_DSJCJ.BLL.DocCls();
        private ElingOA6_DSJCJ.BLL.ClsTempl clsTemplBLL = new ElingOA6_DSJCJ.BLL.ClsTempl();
        private ElingOA6_DSJCJ.BLL.Common commonBLL = new ElingOA6_DSJCJ.BLL.Common();
        private ElingOA6_DSJCJ.BLL.Document documentBLL = new ElingOA6_DSJCJ.BLL.Document();
        private ElingOA6_DSJCJ.BLL.SubOfficeDeptDocCls deptDocClsBLL = new ElingOA6_DSJCJ.BLL.SubOfficeDeptDocCls();
        BLL.SubOfficeDeptDocCls SubOfficeDeptDocClsbll = new BLL.SubOfficeDeptDocCls();
        private ElingOA6_DSJCJ.BLL.HRDept deptBLL = new ElingOA6_DSJCJ.BLL.HRDept();


        private BLL.Entity entityBLL = new BLL.Entity();
        private BLL.Config configBLL = new BLL.Config();
        private BLL.SysPhrase sysPhraseBLL = new BLL.SysPhrase();
        private BLL.ConfigEntry configEntryBLL = new BLL.ConfigEntry();

        BLL.SubOfficeDeptDocClsEntry SubOfficeDeptDocClsEntrybll = new BLL.SubOfficeDeptDocClsEntry();
        public string entityNo = GlobalConstant.ENTITYNO;
        BLL.SubOfficeDeptTemplate depttempbll = new BLL.SubOfficeDeptTemplate();
        BLL.SubOfficeTempCls tempclsbll = new BLL.SubOfficeTempCls();
        BLL.SubOfficeTemplate tempbll = new BLL.SubOfficeTemplate();

        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl(); private BLL.DocRecObject docRecObjectBLL = new BLL.DocRecObject();
        private BLL.DocAttach docAttachBLL = new BLL.DocAttach();
        private BLL.DocReadLog docReadLogBLL = new BLL.DocReadLog();
        private BLL.LinkType linkTypeBLL = new BLL.LinkType();
        private BLL.LinkTypeEntry linkTypeEntryBLL = new BLL.LinkTypeEntry();
        private BLL.DocVote docVoteBLL = new BLL.DocVote();
        private BLL.Ad adBLL = new BLL.Ad();
        private BLL.TaxPeriod taxPeriodBLL = new BLL.TaxPeriod();
        private BLL.HRWatchSchedule HRWatchScheduleBLL = new BLL.HRWatchSchedule();
        private BLL.AccManagerDir AccManagerDirBLL = new BLL.AccManagerDir();
        private BLL.AccManagerDoc AccManagerDocBLL = new BLL.AccManagerDoc();
        //默认模板id
        string defaulttempid = "01";

        public ActionResult Index(string FDeptNo)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            string deptNo = FDeptNo;
            string deptno = FDeptNo;
            Model.SubOfficeDeptTemplate depttemp = depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").Count > 0 ? depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").FirstOrDefault() : null;
            Model.SubOfficeTemplate subtemp = tempbll.GetModelList("FTempID='" + depttemp.FTempID + "'").FirstOrDefault();
            if (subtemp == null)
            {
                subtemp = tempbll.GetModelList("FTempID='" + defaulttempid + "'").FirstOrDefault();
                string templateurl = subtemp.FUrl.Replace("<#Field:FDeptNo>", deptno);
                Response.Write("<script>window.location.href='" + templateurl + "'</script>");
                Response.Flush();
                Response.End();
            }
            else
            {
                string templateurl = subtemp.FUrl.Replace("<#Field:FDeptNo>", deptno);
                Response.Write("<script>window.location.href='" + templateurl + "'</script>");
                Response.Flush();
                Response.End();
            }
            return View();
        }

        /// <summary>
        /// 科室首页
        /// </summary>
        /// <param name="FDeptNo">部门id</param>
        /// <returns></returns>

        public ActionResult Template(string FDeptNo)
        {


            int total = 0;
            string entityNo = GlobalConstant.ENTITYNO;
            string deptNo = FDeptNo;
            string deptno = FDeptNo;
            Dictionary<string, List<ElingOA6_DSJCJ.Models.DocumentGridModel>> dicDocumentList = new Dictionary<string, List<ElingOA6_DSJCJ.Models.DocumentGridModel>>();
            Dictionary<string, string> dicDocClsNameList = new Dictionary<string, string>();
            //当前部门模板
            Model.SubOfficeDeptTemplate depttemp = depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").Count > 0 ? depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").FirstOrDefault() : null;
            ViewData["fmode"] = depttemp == null ? "P" :( depttemp.FTemplTopPicMode=="F"?"F":"P");
            ViewData["logUrl"] = depttemp == null ? "" : depttemp.FTemplTopPicPath;
            BLL.Entity entityBLL = new BLL.Entity();
            //科室的栏目表
            Dictionary<Model.DocCls, List<Model.DocCls>> DicClsAndSub = GetDeptDocClsAndSub(entityNo, deptNo);

            //根据部门获取栏目
            List<Model.SubOfficeDeptDocCls> deptDocClsList = new List<Model.SubOfficeDeptDocCls>();
            deptDocClsList = deptDocClsBLL.GetModelListByDept(entityNo, FDeptNo);
            if (deptDocClsList == null | deptDocClsList.Count == 0)
            {
                //Response.Write("<script>alert('此科室不存在数据');window.close();</script>");
                //Response.Flush();
                //Response.End();
                //return null;
                ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
                ViewData["FDeptNo"] = FDeptNo;//部门编号

                ViewData["CopyRight"] = entityBLL.GetCopyRight(entityNo);

                string deptName = deptBLL.GetDeptName(entityNo, FDeptNo);
                ViewData["FDeptName"] = deptName;
                return View("Template", dicDocumentList); ;
            }
            //List<Model.DocCls> subDocClsList = docClsBLL.GetSubDocClsOneList(deptDocClsList[0].FDocClsCd, GlobalConstant.ENTITYNO);
            ////获取前4条
            //int count = 1;

            //foreach (Model.DocCls deptDocClsModel in subDocClsList)
            //{
            //    if (count <= 6)
            //    {
            //        string tmpClsNo = deptDocClsModel.FDocClsCd;
            //        dicDocumentList.Add(tmpClsNo, GetDocList(8, out total, tmpClsNo, 1));
            //        dicDocClsNameList.Add(tmpClsNo, deptDocClsModel.FDocClsName);
            //    }
            //    count++;
            //}
            //递归产生栏目文档
            int count = 1;
            foreach (KeyValuePair<Model.DocCls, List<Model.DocCls>> vl in DicClsAndSub)
            {
                if (count <= 6)
                {
                    string tmpClsNo = vl.Key.FDocClsCd;
                    dicDocClsNameList.Add(tmpClsNo, vl.Key.FDocClsName);
                    List<Models.DocumentGridModel> alldoc = new List<Models.DocumentGridModel>();

                    alldoc.AddRange(GetDocList(8, out total, vl.Key.FDocClsCd, deptno, 1).ToList());

                    alldoc.Distinct();
                    dicDocumentList.Add(tmpClsNo, alldoc.Take(8).ToList());
                }
                count++;

            }
            ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
            ViewData["FDeptNo"] = FDeptNo;//部门编号

            //获取权属
            entityBLL = new BLL.Entity();
            ViewData["CopyRight"] = entityBLL.GetCopyRight(entityNo);

            string deptName2 = deptBLL.GetDeptName(entityNo, FDeptNo);
            ViewData["FDeptName"] = deptName2;

            //ViewData["templateName"] = "21";
            return View("Template", dicDocumentList); ;
        }

        private Dictionary<Model.DocCls, List<Model.DocCls>> GetDeptDocClsAndSub(string entityNo, string deptNo)
        {
            // List<Model.SubOfficeDeptDocCls> SubOfficeDeptDocClslist = SubOfficeDeptDocClsbll.GetModelList("t_docCls.FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "' ORDER BY dbo.t_docCls.FSeq");
            List<Model.SubOfficeDeptDocCls> SubOfficeDeptDocClslist = SubOfficeDeptDocClsbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'");
            List<Model.SubOfficeDeptDocClsEntry> SubOfficeDeptDocClsEntrylist = SubOfficeDeptDocClsEntrybll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'");
            List<Model.DocCls> alldoclslist = docClsBLL.GetModelList("").Where(h => h.FIsUse == 1).ToList();
            Dictionary<Model.DocCls, List<Model.DocCls>> DicClsAndSub = new Dictionary<Model.DocCls, List<Model.DocCls>>();

            //递归产生一个科室主栏目和同时显示栏目的dic文档对象
            foreach (Model.SubOfficeDeptDocCls mcls in SubOfficeDeptDocClslist)
            {
                //主栏目文档
                Model.DocCls first = docClsBLL.GetModel(entityNo, mcls.FDocClsCd);
                if (first.FIsUse == 0)
                {
                    continue;
                }
                List<Model.DocCls> nextdoclslist = new List<Model.DocCls>();
                nextdoclslist.Add(first);
                List<Model.DocCls> sublist = new List<Model.DocCls>();
                //先取出主栏目的递归文档
                sublist = GetSelfAndChildDocClsEntry(alldoclslist, new List<Model.DocCls>() { first });
                nextdoclslist.AddRange(sublist);
                List<Model.SubOfficeDeptDocClsEntry> subentry = SubOfficeDeptDocClsEntrylist.Where(h => h.FDocClsCd == mcls.FDocClsCd).ToList();
                //递归取出同时显示栏目的递归文档
                foreach (Model.SubOfficeDeptDocClsEntry e in subentry)
                {
                    List<Model.DocCls> entrysublist = new List<Model.DocCls>();
                    Model.DocCls mentry = docClsBLL.GetModel(entityNo, e.FShowDocClsCd);
                    if (mentry != null)
                    {
                        if (mentry.FIsUse == 0)
                        {
                            continue;
                        }
                        else
                        {
                            entrysublist = GetSelfAndChildDocClsEntry(alldoclslist, new List<Model.DocCls>() { mentry });
                            nextdoclslist.AddRange(entrysublist);
                        }
                    }
                }
                DicClsAndSub.Add(first, nextdoclslist.Distinct().ToList());
            }
            return DicClsAndSub;
        }
        //递归子栏目
        public static List<ElingOA6_DSJCJ.Model.DocCls> GetSelfAndChildDocClsEntry(List<ElingOA6_DSJCJ.Model.DocCls> configEntryList, List<ElingOA6_DSJCJ.Model.DocCls> tempEntryLista)
        {
            List<ElingOA6_DSJCJ.Model.DocCls> ts = new List<ElingOA6_DSJCJ.Model.DocCls>();
            foreach (ElingOA6_DSJCJ.Model.DocCls c in tempEntryLista)
            {
                if (configEntryList.Exists(g => g.FPreDocClsCd == c.FDocClsCd) &
                  string.IsNullOrEmpty(c.FPreDocClsCd))
                //!configEntryList.Select(j => j.FPreDocClsCd).Any(q=>configEntryList.Where(h => h.FKeyName == c.FKeyName && h.FPreDocClsCd == c.FDocClsCd).Select(p=>p.FDocClsCd).Contains(q)))
                {
                    List<ElingOA6_DSJCJ.Model.DocCls> t = configEntryList.Where(h => h.FPreDocClsCd == c.FDocClsCd).ToList();
                    ts.AddRange(t);

                }
                else
                {
                    if (!ts.Contains(c) & !configEntryList.Exists(g => g.FPreDocClsCd == c.FDocClsCd))
                    {
                        ts.Add(c);
                    }

                }
            }
            return ts.OrderBy(p => p.FSeq).ToList();
        }
        //生成详情页
        public ActionResult TemplateListDetail(decimal docId, string FDeptNo)
        {
            int total = 0;
            string deptNo = FDeptNo;

            string entityNo = GlobalConstant.ENTITYNO;
            //当前部门模板  
            string deptno = FDeptNo;
            Model.SubOfficeDeptTemplate depttemp = depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").Count > 0 ? depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").FirstOrDefault() : null;
            ViewData["logUrl"] = depttemp == null ? "" : depttemp.FTemplTopPicPath;
            ViewData["fmode"] = depttemp == null ? "P" : (depttemp.FTemplTopPicMode == "F" ? "F" : "P");
            //  Dictionary<string, List<ElingOA6_DSJCJ.Models.DocumentGridModel>> dicDocumentList = new Dictionary<string, List<ElingOA6_DSJCJ.Models.DocumentGridModel>>();
            Dictionary<string, string> dicDocClsNameList = new Dictionary<string, string>();
            Model.Document documentModel = documentBLL.GetModel(docId);

            string clsCd = documentModel.FDocClsCd;
            Model.DocCls docClsModel = docClsBLL.GetModel(GlobalConstant.ENTITYNO, clsCd);
            string preclscd;
            if (!string.IsNullOrEmpty(docClsModel.FPreDocClsCd))
            {

                preclscd = docClsModel.FPreDocClsCd;

            }
            else
            {
                preclscd = docClsModel.FDocClsCd;
            }

            ViewData["docClsCd"] = clsCd;
            ViewData["docClsName"] = docClsModel.FDocClsName;
            if (docClsModel != null)
            {



                //banner
                // ViewData["logUrl"] = docClsModel.FTemplTopPicPath;
                //科室的栏目表
                List<Model.SubOfficeDeptDocCls> SubOfficeDeptDocClslist = SubOfficeDeptDocClsbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'");
                List<Model.SubOfficeDeptDocClsEntry> SubOfficeDeptDocClsEntrylist = SubOfficeDeptDocClsEntrybll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptNo + "'");
                List<Model.DocCls> alldoclslist = docClsBLL.GetModelList("");
                Dictionary<Model.DocCls, List<Model.DocCls>> DicClsAndSub = new Dictionary<Model.DocCls, List<Model.DocCls>>();

                //递归产生一个科室主栏目和同时显示栏目的dic文档对象
                foreach (Model.SubOfficeDeptDocCls mcls in SubOfficeDeptDocClslist)
                {
                    //主栏目文档
                    Model.DocCls first = docClsBLL.GetModel(entityNo, mcls.FDocClsCd);
                    List<Model.DocCls> nextdoclslist = new List<Model.DocCls>();
                    nextdoclslist.Add(first);
                    List<Model.DocCls> sublist = new List<Model.DocCls>();
                    //先取出主栏目的递归文档
                    sublist = GetSelfAndChildDocClsEntry(alldoclslist, new List<Model.DocCls>() { first });
                    nextdoclslist.AddRange(sublist);
                    List<Model.SubOfficeDeptDocClsEntry> subentry = SubOfficeDeptDocClsEntrylist.Where(h => h.FDocClsCd == mcls.FDocClsCd).ToList();
                    //递归取出同时显示栏目的递归文档
                    foreach (Model.SubOfficeDeptDocClsEntry e in subentry)
                    {
                        List<Model.DocCls> entrysublist = new List<Model.DocCls>();
                        Model.DocCls mentry = docClsBLL.GetModel(entityNo, e.FShowDocClsCd);
                        if (mentry != null)
                        {

                            entrysublist = GetSelfAndChildDocClsEntry(alldoclslist, new List<Model.DocCls>() { mentry });
                            nextdoclslist.AddRange(entrysublist);
                        }
                    }
                    DicClsAndSub.Add(first, nextdoclslist.Distinct().ToList());
                }

                //根据部门获取栏目
                List<Model.SubOfficeDeptDocCls> deptDocClsList = new List<Model.SubOfficeDeptDocCls>();
                deptDocClsList = deptDocClsBLL.GetModelListByDept(entityNo, FDeptNo);
                if (deptDocClsList == null | deptDocClsList.Count == 0)
                {
                    //Response.Write("<script>alert('此科室不存在数据');window.close();</script>");
                    //Response.Flush();
                    //Response.End();
                    //return null;
                    ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
                    ViewData["FDeptNo"] = FDeptNo;//部门编号

                    ViewData["CopyRight"] = entityBLL.GetCopyRight(entityNo);

                    string deptName = deptBLL.GetDeptName(entityNo, FDeptNo);
                    ViewData["FDeptName"] = deptName;
                    return null;
                }


                int count = 1;

                //递归导航条栏目名
                foreach (KeyValuePair<Model.DocCls, List<Model.DocCls>> vl in DicClsAndSub)
                {
                    if (count <= 6)
                    {
                        string tmpClsNo = vl.Key.FDocClsCd;
                        dicDocClsNameList.Add(tmpClsNo, vl.Key.FDocClsName);

                    }
                    count++;

                }
                ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
                ViewData["FDeptNo"] = FDeptNo;//部门编号

                //获取权属
                entityBLL = new BLL.Entity();
                ViewData["CopyRight"] = entityBLL.GetCopyRight(entityNo);

                string deptName2 = deptBLL.GetDeptName(entityNo, FDeptNo);
                ViewData["FDeptName"] = deptName2;

            }




            return DocView(docId, "TemplateListDetail");
        }
        /// <summary>
        /// 科室导航详情页
        /// </summary>
        /// <param name="clsCd">栏目id</param>
        /// <param name="FDeptNo">部门id</param>
        /// <param name="id">分页id</param>
        /// <returns></returns>
        public ActionResult TemplateList(string clsCd, string FDeptNo, int id = 1)
        {
            int pageSize = 20;
            int total=0;
            string entityNo = GlobalConstant.ENTITYNO;
            Model.DocCls docClsModel = docClsBLL.GetModel(GlobalConstant.ENTITYNO, clsCd);
            string preclscd;

            preclscd = docClsModel.FDocClsCd;
            string deptNo = FDeptNo;
            //当前部门模板  
            string deptno = FDeptNo;
            Model.SubOfficeDeptTemplate depttemp = depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").Count > 0 ? depttempbll.GetModelList("FEntityNo='" + entityNo + "' and FDeptNo='" + deptno + "'").FirstOrDefault() : null;
            ViewData["logUrl"] = depttemp == null ? "" : depttemp.FTemplTopPicPath;
            ViewData["docClsCd"] = preclscd;
            ViewData["fmode"] = depttemp == null ? "P" : (depttemp.FTemplTopPicMode == "F" ? "F" : "P");
            //当前栏目名 
            ViewData["docClsName"] = docClsModel.FDocClsName;



            Dictionary<string, List<ElingOA6_DSJCJ.Models.DocumentGridModel>> dicDocumentList = new Dictionary<string, List<ElingOA6_DSJCJ.Models.DocumentGridModel>>();
            Dictionary<string, string> dicDocClsNameList = new Dictionary<string, string>();

            BLL.Entity entityBLL = new BLL.Entity();
            Dictionary<Model.DocCls, List<Model.DocCls>> DicClsAndSub = GetDeptDocClsAndSub(entityNo, deptNo);
            if (DicClsAndSub.Count == 1)
            {
                int count = 1;
                //递归取栏目文档
                List<Models.DocumentGridModel> docGridList = new List<Models.DocumentGridModel>();
                foreach (KeyValuePair<Model.DocCls, List<Model.DocCls>> vl in DicClsAndSub)
                {
                    if (count <= 6)
                    {
                        string tmpClsNo = vl.Key.FDocClsCd;
                        dicDocClsNameList.Add(tmpClsNo, vl.Key.FDocClsName);
                        if (vl.Key.FDocClsCd == clsCd)
                        {


                            docGridList.AddRange(GetDocList(pageSize, out total, vl.Key.FDocClsCd, deptno, id).ToList());

                        }
                    }
                    count++;
                }
                //根据时间排序
                docGridList.OrderBy(h => h.FPubDate).Distinct();
                ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
                ViewData["CopyRight"] = entityBLL.GetCopyRight(entityNo);
                ViewData["focusCd"] = docClsModel.FDocClsCd;
                ViewData["FDeptNo"] = FDeptNo;//部门编号
                string deptName = deptBLL.GetDeptName(entityNo, FDeptNo);
                ViewData["FDeptName"] = deptName;
               
                //分页
                // List<Models.DocumentGridModel> docGridList2 = docGridList.Skip(id * 20 - 20).Take(20).ToList();
                PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);
                return View("TemplateListSingle", documentList);
            }
            else
            {
                //当多栏目时
                string docClsHtml = "<ul>";

                int count = 1;
                List<Models.DocumentGridModel> docGridList = new List<Models.DocumentGridModel>();
                //生成导航树
                foreach (KeyValuePair<Model.DocCls, List<Model.DocCls>> vl in DicClsAndSub)
                {
                    //if (count <= 6)
                    //{
                        docClsHtml += "<li><h2><a href='/SubOffice/TemplateList?clsCd=" + vl.Key.FDocClsCd.ToString() + "&FDeptNo=" + FDeptNo;
                        docClsHtml += "' >" + vl.Key.FDocClsName.ToString() + "</a><span>&gt;</span></h2></li>";
                        string tmpClsNo = vl.Key.FDocClsCd;
                        dicDocClsNameList.Add(tmpClsNo, vl.Key.FDocClsName);
                        if (vl.Key.FDocClsCd == clsCd)
                        {

                            docGridList.AddRange(GetDocList(pageSize, out total, tmpClsNo, deptno, id).ToList());

                        }
                   // }
                    count++;

                }
                //根据时间排序
                docGridList.OrderBy(h => h.FPubDate).Distinct();
                docClsHtml += "</ul>";

                ViewData["docClsHtml"] = docClsHtml;
                ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
                ViewData["CopyRight"] = entityBLL.GetCopyRight(entityNo);
                ViewData["focusCd"] = docClsModel.FDocClsCd;
                ViewData["FDeptNo"] = FDeptNo;//部门编号
                string deptName = deptBLL.GetDeptName(entityNo, FDeptNo);
                ViewData["FDeptName"] = deptName;
               
                //total = 0;
                //分页
               // List<Models.DocumentGridModel> docGridList2 = docGridList.Skip(id * 20 - 20).Take(20).ToList();
                PagedList<Models.DocumentGridModel> documentList = new PagedList<Models.DocumentGridModel>(docGridList, id, pageSize, total);

                return View("TemplateList", documentList);
            }


        }



        public ActionResult DocView(decimal docId, string viewName = "")
        {

            // ViewData["logUrl"] = "";//专题专栏top图片地址
            string entityNo = GlobalConstant.ENTITYNO;
            Model.Document documentModel = documentBLL.GetModel(docId);
            if (documentModel != null)
            {

                Model.DocCls docClsModel1 = docClsBLL.GetModel(entityNo, documentModel.FDocClsCd);
                if (docClsModel1 != null)
                {
                    ViewData["docName"] = docClsModel1.FDocClsName;
                }
                ViewData["FDocId"] = documentModel.FDocId;
                ViewData["navi"] = "当前位置：首页 > " + ViewData["docName"].ToString();
                //发布部门名称
                BLL.HRDept hrDeptBLL = new BLL.HRDept();
                documentModel.FDeptName = hrDeptBLL.GetDeptName(entityNo, documentModel.FDeptNo);
                //发布人
                BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
                documentModel.FEmpName = hrEmplBLL.GetEmpName(entityNo, documentModel.FEmplNo);
                //获取信息类别
                string docClsCd = "";

                docClsCd = documentModel.FDocClsCd;


                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    // ViewData["logUrl"] = GetTemplTopPicPath(docClsModel);
                    string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    bool isLook = true;//是否可查看
                    bool isAddReadLog = false;//是否需要插入信息文档查看记录
                    string url = "";
                    string newofficetype = "1";//默认office文档类型
                   documentModel.FContentTxt = documentModel.FContentTxt.Replace("&nbsp;&nbsp;&nbsp;&nbsp;", "　");//替换成中文的空格
                    //上传图片
                    List<Model.DocAttach> docAttachPicList = docAttachBLL.GetDocAttachListByDocID(docId, "PIC");
                    string strView = "";
                    if (docAttachPicList.Count > 0)
                    {
                        strView += "<div style='text-align: center'>";
                        foreach (Model.DocAttach docAttachModel in docAttachPicList)
                        {
                            strView += "<img alt='' width='600' height='400' src='" + Url.Action("IndexImageWithDocid", "Index", new { pt = docAttachModel.FAttachSvrFileName, docid = docId }) + "' /><br /><br />";
                        }
                        strView += "</div>";
                    }
                    documentModel.FContentTxt = strView + documentModel.FContentTxt;

                    if (documentModel.FIsEnroll == "N" || documentModel.FRecycle == "Y")
                    {
                        isLook = false;
                    }
                    else
                    {

                        //是否控制查看权限
                        if (docClsModel.FIsCtrlLookAuthority == "Y")
                        {
                            if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                            {
                                //控制到信息 everyone可见的
                                if (docClsModel.FLookAuthorityMode == "D" && documentBLL.IsDocumentAuthorityForEveryone(docId))
                                {
                                    isLook = true;
                                }
                                else
                                {
                                    isLook = false;
                                }
                            }
                            else
                            {
                                //判断是否控制到信息
                                if (docClsModel.FLookAuthorityMode == "D")
                                {
                                    if (documentBLL.IsDocumentAuthorityForEmpl(empNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }

                                }
                                else//控制到栏目
                                {
                                    if (documentBLL.IsDocAuthorityForEmpl(empNo, docClsCd, entityNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //判断是否通知对象
                            if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                            {
                                isAddReadLog = true;
                            }
                        }
                    }
                    if (!isLook)
                    {
                        Response.Write("<script>alert('你无权限查看该信息');window.close();</script>");
                        Response.Flush();
                        Response.End();
                        return null;
                    }
                    else
                    {
                        if (documentModel.FEditMode == "O")
                        {
                            url = "/" + documentModel.FSvrFileName.Substring(1);
                            string extension = url.Substring(url.LastIndexOf('.') + 1).ToUpper();
                            switch (extension)
                            {
                                case "DOC":
                                    newofficetype = "1";
                                    break;
                                case "DOCX":
                                    newofficetype = "1";
                                    break;
                                case "XLS":
                                    newofficetype = "2";
                                    break;
                                case "XLSX":
                                    newofficetype = "2";
                                    break;
                                case "PPT":
                                    newofficetype = "3";
                                    break;
                                case "PPTX":
                                    newofficetype = "3";
                                    break;
                                default:
                                    newofficetype = "1";
                                    break;
                            }

                        }

                        //获取权属
                        BLL.Entity entityBLL = new BLL.Entity();
                        ViewData["CopyRight"] = entityBLL.GetCopyRight(GlobalConstant.ENTITYNO);

                        //附件
                        List<Model.DocAttach> docAttachList = docAttachBLL.GetDocAttachListByDocID(docId, "DOC");// attachBll.GetList(GlobalConstant.CONSTRING_ENTITYNO, docID, "DOC");

                        ViewData["docAttach"] = docAttachList;
                        try
                        {
                            documentBLL.UpdateReadCntByDocId(docId); //更新查看次数
                            documentModel.FReadCnt++;
                        }
                        catch
                        {

                        }

                        ViewData["url"] = url;
                        ViewData["newofficetype"] = newofficetype;

                        if (null == OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION) || null == OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY))
                        {
                            //从数据库获取Ntko Office控件序列号
                            BLL.Entity entityBll = new BLL.Entity();
                            Model.Entity entityModel = entityBll.GetModel(GlobalConstant.ENTITYNO);
                            if (entityModel != null)
                            {
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                            }
                        }


                        ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
                        ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);

                        if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                        {
                            //未登录

                        }
                        else
                        {
                            //已登录
                            //获取部门信息
                            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            string deptName = "";
                            string empName = "";
                            if (emplNo != "" && entityNo != "")
                            {
                                DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    DataTable dt = ds.Tables[0];
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                                        {
                                            ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                            ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                            deptName = ViewData["DeptName"].ToString();
                                            empName = ViewData["EmpName"].ToString();
                                            OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                            break;
                                        }

                                    }
                                }
                            }
                            if (isAddReadLog)
                            {
                                //判断是否已经阅读
                                if (!docReadLogBLL.Exists(entityNo, docId, empNo))
                                {
                                    //插入信息文档查看记录
                                    Model.DocReadLog docReadLogModel = new Model.DocReadLog();
                                    docReadLogModel.FEntityNo = entityNo;
                                    docReadLogModel.FDocId = docId;
                                    docReadLogModel.FDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                    docReadLogModel.FDeptName = deptName;
                                    docReadLogModel.FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                                    docReadLogModel.FEmpName = empName;
                                    docReadLogModel.FReadTime = DateTime.Now;
                                    docReadLogModel.FIPAddr = Request.UserHostAddress;
                                    try
                                    {
                                        docReadLogBLL.Add(docReadLogModel);
                                    }
                                    catch
                                    {

                                    }
                                }
                            }
                        }
                        ViewData["isVote"] = docClsModel.FIsVote;


                        //获取批示权限
                        if (docClsModel.FIsExamine == "Y")
                        {
                            BLL.PrvUser prvUserBll = new BLL.PrvUser();
                            Model.PrvUser prvUserModel = prvUserBll.GetModel(OperateSession.get(GlobalConstant.PARAM_LOGINID), GlobalConstant.ENTITYNO);
                            string fisIns = "";
                            if (prvUserModel != null)
                            {
                                fisIns = prvUserModel.FIsInstruct;
                            }
                            ViewData["FIsInstruct"] = fisIns == null ? "" : fisIns;
                            ViewData["FEmplNo"] = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            if (ViewData["FEmplNo"] == null)
                            {
                                ViewData["FEmplNo"] = "";
                            }

                            //获取领导批示列表
                            BLL.LeadInstruct leadInstructBLL = new BLL.LeadInstruct();
                            string strWhere = "FDocId=" + documentModel.FDocId + " and a.FEntityNo='" + GlobalConstant.ENTITYNO + "'";
                            DataSet dslt = leadInstructBLL.GetList(strWhere);
                            ViewData["leadInstruct"] = dslt;
                            ViewData["FDocId"] = documentModel.FDocId;
                        }

                        ViewData["FIsExamine"] = docClsModel.FIsExamine != "Y" ? "N" : "Y";

                        //处理图片
                        string pattern1 = "width\\s?=\\s?\"(\\d+)\"\\s+height\\s?=\\s?\"(\\d+)";
                        string pattern2 = "width\\s?:\\s?(\\d+)px;\\s+height\\s?:\\s?(\\d+)px";
                        int matchType = 0;
                        //利用正则替换内容模块
                        MatchCollection tdMatchs = Regex.Matches(documentModel.FContentTxt,
                        @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>",
                        RegexOptions.IgnoreCase | RegexOptions.Multiline);

                        for (int i = tdMatchs.Count - 1; i >= 0; i--)
                        {
                            string oldimgUrl = tdMatchs[i].Value;
                            MatchCollection tdMatchsTmp = Regex.Matches(oldimgUrl,
                        pattern1, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            if (tdMatchsTmp.Count == 0)
                            {
                                tdMatchsTmp = Regex.Matches(oldimgUrl,
                       pattern2, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                matchType = 2;
                            }
                            else
                            {
                                matchType = 1;
                            }
                            if (tdMatchsTmp.Count > 0)
                            {

                                string imgSizeValue = tdMatchsTmp[0].Value;
                                string width = tdMatchsTmp[0].Groups[1].Value; //宽    
                                string height = tdMatchsTmp[0].Groups[2].Value; //高 
                                int _width = 0;
                                int _height = 0;
                                int newWidth = 0;
                                int newHeight = 0;
                                if (int.TryParse(width, out _width) && int.TryParse(height, out _height))
                                {
                                    if (_width > GlobalConstant.IMG_SHOW_MAXWIDTH)
                                    {
                                        newWidth = GlobalConstant.IMG_SHOW_MAXWIDTH;
                                        newHeight = (_height * GlobalConstant.IMG_SHOW_MAXWIDTH) / _width;
                                        string newImgUrl = "";
                                        if (matchType == 1)
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width='" + newWidth + "' height='" + newHeight + "'");
                                        }
                                        else
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width:" + newWidth + "px; height:" + newHeight + "px");
                                        }
                                        documentModel.FContentTxt = documentModel.FContentTxt.Replace(oldimgUrl, newImgUrl);
                                    }
                                }

                            }
                        }


                        //获取此文档被引用的栏目
                        BLL.DocRefImp docRefImp = new BLL.DocRefImp();
                        List<Model.DocRefImp> docRefImpList = docRefImp.GetListByDocId(GlobalConstant.ENTITYNO, docId);
                        string docRefImpClsName = "";
                        if (docRefImpList.Count > 0)
                        {
                            List<CommonValueModel> commValueList = new List<CommonValueModel>();
                            foreach (Model.DocRefImp docRefImpModel in docRefImpList)
                            {
                                commValueList.Add(new CommonValueModel { Text = docRefImpModel.FDocClsName, Value = docRefImpModel.FDocClsCd });
                                docRefImpClsName += docRefImpModel.FDocClsName + ",";
                            }

                            if (docRefImpClsName != "")
                            {
                                docRefImpClsName = "此信息已被下列栏目引用：" + docRefImpClsName.Trim(',');
                            }

                            ViewData["docRefImpClsName"] = docRefImpClsName;
                            ViewData["docRefImpClsJson"] = JsonConvert.SerializeObject(commValueList);
                        }
                        else
                        {
                            ViewData["docRefImpClsName"] = "";
                            ViewData["docRefImpClsJson"] = "";
                        }




                        if (viewName == "")
                        {
                            return View("DocView", documentModel);
                        }
                        else
                        {
                            return View(viewName, documentModel);
                        }
                    }

                }
                else
                {
                    Response.Write("<script>alert('对应信息类别不存在');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }

            }
            else
            {
                Response.Write("<script>alert('信息不存在');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }


        private void SetDocClsHtml(string FDeptNo, string clsCd, ref string docClsHtml, DataTable deptDocClsDT, string preDocClsNo, string template)
        {
            string entityNo = Common.GlobalConstant.ENTITYNO;
            var tmpDocCls = deptDocClsDT.Select("FPreDocClsCd='" + preDocClsNo + "'").ToList();
            if (tmpDocCls.Count() > 0)
            {
                docClsHtml += "<ul class='sup'>";
                foreach (DataRow dr in tmpDocCls)
                {
                    if (dr["FDocClsProp"].ToString() == "2")
                    {
                        //单信息
                        decimal ShowDocId = documentBLL.GetDocIdDocClsCd(entityNo, dr["FDocClsCd"].ToString());
                        docClsHtml += "<li><a href='/SubOffice/Template_JGJJDetail?docId=" + ShowDocId +
                                                            "&FDeptNo=" + FDeptNo + "&template=" + template
                                                            + "' target='contentFrm' >" + dr["FDocClsName"].ToString() + "</a></li>";
                        //SetDocClsHtml(docClsHtml, configDocClsDT, dr["FDocClsCd"].ToString());
                        if (clsCd == dr["FDocClsCd"].ToString())
                        {
                            ViewData["ShowDocId"] = ShowDocId;
                        }

                    }
                    else
                    {
                        docClsHtml += "<li><a href='/SubOffice/Template_List?FDeptNo=" + FDeptNo +
                                                               "&template=" + template + "&docClsCd=" + dr["FDocClsCd"].ToString()
                                                               + "' target='contentFrm' >" + dr["FDocClsName"].ToString() + "</a></li>";
                        //SetDocClsHtml(docClsHtml, configDocClsDT, dr["FDocClsCd"].ToString());
                    }

                    //if (clsCd == dr["FDocClsCd"].ToString())
                    //{
                    //    //如果显示栏目时 单信息，则右边为详细信息页
                    //    Model.DocCls showDocClsModel = docClsBLL.GetModel(entityNo, clsCd);
                    //    if (showDocClsModel != null)
                    //    {
                    //        if (showDocClsModel.FDocClsProp == "2")
                    //        {
                    //            //单信息
                    //            decimal ShowDocId = documentBLL.GetDocIdDocClsCd(entityNo, clsCd);
                    //            ViewData["ShowDocId"] = ShowDocId;


                    //        }
                    //        else
                    //        {

                    //        }
                    //    }
                    //}

                }
                docClsHtml += "</ul>";


            }
        }








        /// <summary>
        /// 列表页
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="total"></param>
        /// <param name="pageIndex"></param>
        /// <param name="docClsCd"></param>
        private List<Models.DocumentGridModel> GetDocList(int pageSize, out int total, string docClsCd, string deptNo, int pageIndex = 1)
        {
            bool isLogin = string.IsNullOrEmpty(OperateSession.get(GlobalConstant.PARAM_LOGINID)) ? false : true;
            total = 0;
            List<Models.DocumentGridModel> documentList = new List<Models.DocumentGridModel>();
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            string fieldOrder = " FIsTop DESC,FTopSeq ASC,FDisplayDate";
            if (isLogin)
            {
                //已登录
                //栏目: 1、不控制查看权限 或者 2、控制查看权限，公开标题 或者 3、控制查看权限，不公开标题，有权限
                string strWhere = "";
                string fiedls = "*";
                string tableName = "";
                tableName = "dbo.fn_GetIndexDocument_DocClsCd__DeptNo_ByCTE_Login('" + GlobalConstant.ENTITYNO + "','" + empNo + "','" + docClsCd + "','" + deptNo + "')";

                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);
            }
            else
            {
                //未登录
                //栏目：1、不控制查看权限 或者 2、控制查看权限，公开标题
                string strWhere = "";
                string fiedls = "*";
                string tableName = "";
                tableName = "dbo.fn_GetIndexDocument_DocClsCd_DeptNo_ByCTE_NotLogin('" + GlobalConstant.ENTITYNO + "','" + docClsCd + "','" + deptNo + "')";

                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageSize, pageIndex, strWhere, fieldOrder, 1, out total);
                documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);
            }
            return documentList;
        }

        /// <summary>
        /// 头部
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 1, VaryByParam = "none")]
        public ActionResult Top(string template)
        {
            int showCount = 6;
            if (template == "tw4" || template == "tw5")//丹城分局，城郊分局显示8个
            {
                showCount = 8;
            }

            //页眉链接
            List<Model.Config> configList = configBLL.GetListAllIsUse(GlobalConstant.ENTITYNO);


            string FDeptNo = Request.QueryString["FDeptNo"];
            string entityNo = GlobalConstant.ENTITYNO;
            string deptName = deptBLL.GetDeptName(entityNo, FDeptNo);


            Dictionary<string, string> dicDocClsNameList = new Dictionary<string, string>();


            //根据部门获取栏目
            List<Model.SubOfficeDeptDocCls> deptDocClsList = new List<Model.SubOfficeDeptDocCls>();
            deptDocClsList = deptDocClsBLL.GetModelListByDept(entityNo, FDeptNo);

            //获取前4条
            int count = 1;

            foreach (Model.SubOfficeDeptDocCls deptDocClsModel in deptDocClsList)
            {
                if (count <= showCount)
                {
                    string tmpClsNo = deptDocClsModel.FDocClsCd;
                    dicDocClsNameList.Add(tmpClsNo, deptDocClsModel.FDocClsName);
                }
                count++;
            }
            ViewData["dicDocClsNameList"] = dicDocClsNameList;//栏目名称集合
            ViewData["FDeptNo"] = FDeptNo;
            ViewData["FDeptName"] = deptName;
            ViewData["templateName"] = template;



            //地税分局log加上此名字
            string dsfjDocCls = System.Web.Configuration.WebConfigurationManager.AppSettings["dsfjDocCls"];
            string[] dsfjDocClsList = dsfjDocCls.Split(',');
            if (dsfjDocClsList.Contains(FDeptNo))
            {
                ViewData["logName"] = "象山县地方税务局";
            }

            if (template == "tw4")//如果是丹城分局
            {
                return PartialView("dcfjTop", configList);
            }
            else if (template == "tw5")//如果是城郊分局
            {
                return PartialView("cjfjTop", configList);
            }
            else
            {
                return PartialView(configList);
            }
        }

        /// <summary>
        /// 底部
        /// </summary>
        /// <returns></returns>
        [OutputCache(Duration = 1, VaryByParam = "none")]
        public ActionResult Bottom()
        {
            string entityNo = GlobalConstant.ENTITYNO;


            ViewData["CopyRight"] = entityBLL.GetCopyRight(GlobalConstant.ENTITYNO);
            return PartialView();
        }



        public ActionResult Template_DocumentIndex(string FDeptNo, string template, string indexClsCd = "")
        {
            ActionResult actionResult = null;
            string entityNo = GlobalConstant.ENTITYNO;
            string deptName = deptBLL.GetDeptName(entityNo, FDeptNo);
            ViewData["FDeptNo"] = FDeptNo;
            ViewData["FDeptName"] = deptName;



            string docClsHtml = "";
            DataTable deptDocClsDT = configEntryBLL.GetDeptDocCls(entityNo, FDeptNo);
            var tmpDocCls = deptDocClsDT.Select("ClsLevel=0").ToList();
            if (deptDocClsDT.Rows.Count == 0)
            {
                Response.Write("<script>alert('该分局无对应栏目信息');</script>");
                Response.Flush();
                Response.End();
            }
            else
            {
                if (deptDocClsDT.Rows.Count == 1 || (tmpDocCls.Count() == 1 && deptDocClsDT.Rows.Count == 2))
                {
                    //不显示左边的树
                    //ViewData["docClsCd"] = tmpDocCls[0]["FDocClsCd"].ToString();
                    string docClsCd = tmpDocCls[0]["FDocClsCd"].ToString();
                    Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        if (docClsModel.FDocClsProp == "2")
                        {
                            //单信息
                            decimal docId = documentBLL.GetDocIdDocClsCd(entityNo, docClsCd);
                            if (docId > 0)
                            {
                                actionResult = Template_Detail(docId, FDeptNo, template);
                            }
                        }
                    }

                }
                else
                {
                    if (tmpDocCls.Count() == 1)
                    {
                        //去除0层的节点
                        deptDocClsDT.Rows.Remove(tmpDocCls[0]);
                        tmpDocCls = deptDocClsDT.Select("ClsLevel=1").ToList();
                    }
                    else
                    {
                        tmpDocCls = deptDocClsDT.Select("ClsLevel<0 ").ToList();
                        if (tmpDocCls.Count() == 0)
                        {
                            tmpDocCls = deptDocClsDT.Select("ClsLevel=0 ").ToList();
                        }
                        else
                        {
                            tmpDocCls = deptDocClsDT.Select("ClsLevel<0 OR FPreDocClsCd IS NULL OR FPreDocClsCd='001' ", "FSeq,FDocClsCd").ToList();

                        }
                    }
                    //循环绑定
                    if (tmpDocCls.Count() > 0)
                    {
                        docClsHtml += "<ul>";
                        if (indexClsCd == "")
                        {
                            indexClsCd = tmpDocCls[0]["FDocClsCd"].ToString();
                        }
                        foreach (DataRow dr in tmpDocCls)
                        {
                            docClsHtml += "<li><h2><a href='/SubOffice/Template_DocumentIndex?FDeptNo=" + FDeptNo + "&template=" + template
                                + "&indexClsCd=" + dr["FDocClsCd"].ToString() + "&docClsCd=" + dr["FDocClsCd"].ToString()
                                + "' >" + dr["FDocClsName"].ToString() + "</a></h2></li>";

                            //docClsHtml += "<li><a href='/Index/DocList?keyName=" + keyName +
                            //  "&keyClass=" + keyClass + "&docClsCd=" + dr["FDocClsCd"].ToString()
                            //  + "' target='contentFrm' >" + dr["FDocClsName"].ToString() + "</a></li>";
                            if (indexClsCd == dr["FDocClsCd"].ToString())
                            {
                                SetDocClsHtml(FDeptNo, Fetch.Get("clsCd"), ref docClsHtml, deptDocClsDT, dr["FDocClsCd"].ToString(), template);

                                //如果显示栏目时 单信息，则右边为详细信息页
                                Model.DocCls showDocClsModel = docClsBLL.GetModel(entityNo, indexClsCd);
                                if (showDocClsModel != null)
                                {
                                    if (showDocClsModel.FDocClsProp == "2")
                                    {
                                        //单信息
                                        decimal ShowDocId = documentBLL.GetDocIdDocClsCd(entityNo, indexClsCd);
                                        ViewData["ShowDocId"] = ShowDocId;
                                    }
                                }
                            }
                        }

                        docClsHtml += "</ul>";
                    }
                }
                if (actionResult == null)
                {
                    ViewData["docClsHtml"] = docClsHtml;

                    actionResult = View();
                }
            }

            string clsCd = Request.QueryString["clsCd"];
            if (clsCd != null)
            {
                ViewData["docClsCd"] = clsCd;
            }
            else
            {
                ViewData["docClsCd"] = indexClsCd;
            }

            ViewData["templateName"] = template;
            return actionResult;
        }

        public ActionResult Template_Detail(decimal docId, string FDeptNo, string template)
        {
            ActionResult actionResult = null;


            IndexController indexCl = new IndexController();
            actionResult = DocView(docId, "Template_Detail", FDeptNo, template);
            return actionResult;
        }
        public ActionResult DocView(decimal docId, string viewName = "", string FDeptNo = "", string template = "")
        {
            ViewData["logUrl"] = "";//专题专栏top图片地址
            string entityNo = GlobalConstant.ENTITYNO;
            Model.Document documentModel = documentBLL.GetModel(docId);
            if (documentModel != null)
            {
                ViewData["FDocId"] = documentModel.FDocId;

                //分局页面专用
                if (FDeptNo != "")
                {
                    ViewData["FDeptNo"] = FDeptNo;
                }

                //发布部门名称
                BLL.HRDept hrDeptBLL = new BLL.HRDept();
                documentModel.FDeptName = hrDeptBLL.GetDeptName(entityNo, documentModel.FDeptNo);
                //发布人
                BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
                documentModel.FEmpName = hrEmplBLL.GetEmpName(entityNo, documentModel.FEmplNo);
                //获取信息类别
                string docClsCd = documentModel.FDocClsCd;

                Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                if (docClsModel != null)
                {
                    ViewData["docClsName"] = docClsModel.FDocClsName;
                    ViewData["logUrl"] = GetTemplTopPicPath(docClsModel);
                    string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                    string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                    bool isLook = true;//是否可查看
                    bool isAddReadLog = false;//是否需要插入信息文档查看记录
                    string url = "";
                    string newofficetype = "1";//默认office文档类型
                    documentModel.FContentTxt = documentModel.FContentTxt.Replace("&nbsp;&nbsp;&nbsp;&nbsp;", "　");//替换成中文的空格
                    //上传图片
                    List<Model.DocAttach> docAttachPicList = docAttachBLL.GetDocAttachListByDocID(docId, "PIC");
                    ViewData["docAttachPicList"] = docAttachPicList;
                    //string strView = "";
                    //if (docAttachPicList.Count > 0)
                    //{
                    //    strView += "<div style='text-align: center'>";
                    //    foreach (Model.DocAttach docAttachModel in docAttachPicList)
                    //    {
                    //        strView += "<img alt='' width='600' height='400' src='" + Url.Action("IndexImage", "Index", new { id = docAttachModel.FAttachID }) + "' /><br /><br />";
                    //    }
                    //    strView += "</div>";
                    //}
                    //documentModel.FContentTxt = strView + documentModel.FContentTxt;

                    if (documentModel.FIsEnroll == "N" || documentModel.FRecycle == "Y")
                    {
                        isLook = false;
                    }
                    else
                    {

                        //是否控制查看权限
                        if (docClsModel.FIsCtrlLookAuthority == "Y")
                        {
                            if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                            {
                                //控制到信息 everyone可见的
                                if (docClsModel.FLookAuthorityMode == "D" && documentBLL.IsDocumentAuthorityForEveryone(docId))
                                {
                                    isLook = true;
                                }
                                else
                                {
                                    isLook = false;
                                }
                            }
                            else
                            {
                                //判断是否控制到信息
                                if (docClsModel.FLookAuthorityMode == "D")
                                {
                                    if (documentBLL.IsDocumentAuthorityForEmpl(empNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }

                                }
                                else//控制到栏目
                                {
                                    if (documentBLL.IsDocAuthorityForEmpl(empNo, docClsCd, entityNo, docId))
                                    {
                                        //判断是否通知对象
                                        if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                                        {
                                            isAddReadLog = true;
                                        }
                                    }
                                    else
                                    {
                                        isLook = false;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //判断是否通知对象
                            if (docRecObjectBLL.Exists(entityNo, docId, empNo))
                            {
                                isAddReadLog = true;
                            }
                        }
                    }
                    if (!isLook)
                    {
                        Response.Write("<script>alert('你无权限查看该信息');window.close();</script>");
                        Response.Flush();
                        Response.End();
                        return null;
                    }
                    else
                    {
                        if (documentModel.FEditMode == "O")
                        {
                            url = "/" + documentModel.FSvrFileName.Substring(1);
                            string extension = url.Substring(url.LastIndexOf('.') + 1).ToUpper();
                            switch (extension)
                            {
                                case "DOC":
                                    newofficetype = "1";
                                    break;
                                case "DOCX":
                                    newofficetype = "1";
                                    break;
                                case "XLS":
                                    newofficetype = "2";
                                    break;
                                case "XLSX":
                                    newofficetype = "2";
                                    break;
                                case "PPT":
                                    newofficetype = "3";
                                    break;
                                case "PPTX":
                                    newofficetype = "3";
                                    break;
                                default:
                                    newofficetype = "1";
                                    break;
                            }

                        }

                        //获取权属
                        BLL.Entity entityBLL = new BLL.Entity();
                        ViewData["CopyRight"] = entityBLL.GetCopyRight(GlobalConstant.ENTITYNO);

                        //附件
                        List<Model.DocAttach> docAttachList = docAttachBLL.GetDocAttachListByDocID(docId, "DOC");// attachBll.GetList(GlobalConstant.CONSTRING_ENTITYNO, docID, "DOC");

                        ViewData["docAttach"] = docAttachList;
                        try
                        {
                            documentBLL.UpdateReadCntByDocId(docId); //更新查看次数
                            documentModel.FReadCnt++;
                        }
                        catch
                        {

                        }

                        ViewData["url"] = url;
                        ViewData["newofficetype"] = newofficetype;

                        if (null == OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION) || null == OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY))
                        {
                            //从数据库获取Ntko Office控件序列号
                            BLL.Entity entityBll = new BLL.Entity();
                            Model.Entity entityModel = entityBll.GetModel(GlobalConstant.ENTITYNO);
                            if (entityModel != null)
                            {
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTKEY, entityModel.FNTKOKey);
                                OperateSession.add(GlobalConstant.PARAM_PRODUCTCAPTION, entityModel.FNTKOCaption);
                            }
                        }


                        ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
                        ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);

                        if (string.IsNullOrEmpty(empNo) || string.IsNullOrEmpty(deptNo))
                        {
                            //未登录

                        }
                        else
                        {
                            //已登录
                            //获取部门信息
                            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            string deptName = "";
                            string empName = "";
                            if (emplNo != "" && entityNo != "")
                            {
                                DataSet ds = hrEmplBLL.GetEmplFromViewByEmplNo(emplNo, entityNo);
                                if (ds.Tables[0].Rows.Count > 0)
                                {
                                    DataTable dt = ds.Tables[0];
                                    for (int i = 0; i < dt.Rows.Count; i++)
                                    {
                                        if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                                        {
                                            ViewData["EmpName"] = dt.Rows[i]["FEmpName"].ToString();
                                            ViewData["DeptName"] = dt.Rows[i]["FDeptName"].ToString();
                                            deptName = ViewData["DeptName"].ToString();
                                            empName = ViewData["EmpName"].ToString();
                                            OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                                            break;
                                        }

                                    }
                                }
                            }
                            if (isAddReadLog)
                            {
                                //判断是否已经阅读
                                if (!docReadLogBLL.Exists(entityNo, docId, empNo))
                                {
                                    //插入信息文档查看记录
                                    Model.DocReadLog docReadLogModel = new Model.DocReadLog();
                                    docReadLogModel.FEntityNo = entityNo;
                                    docReadLogModel.FDocId = docId;
                                    docReadLogModel.FDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                    docReadLogModel.FDeptName = deptName;
                                    docReadLogModel.FEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                                    docReadLogModel.FEmpName = empName;
                                    docReadLogModel.FReadTime = DateTime.Now;
                                    docReadLogModel.FIPAddr = Request.UserHostAddress;
                                    try
                                    {
                                        docReadLogBLL.Add(docReadLogModel);
                                    }
                                    catch
                                    {

                                    }
                                }
                            }
                        }
                        ViewData["isVote"] = docClsModel.FIsVote;


                        //获取批示权限
                        if (docClsModel.FIsExamine == "Y")
                        {
                            BLL.PrvUser prvUserBll = new BLL.PrvUser();
                            Model.PrvUser prvUserModel = prvUserBll.GetModel(OperateSession.get(GlobalConstant.PARAM_LOGINID), GlobalConstant.ENTITYNO);
                            string fisIns = "";
                            if (prvUserModel != null)
                            {
                                fisIns = prvUserModel.FIsInstruct;
                            }
                            ViewData["FIsInstruct"] = fisIns == null ? "" : fisIns;
                            ViewData["FEmplNo"] = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            if (ViewData["FEmplNo"] == null)
                            {
                                ViewData["FEmplNo"] = "";
                            }

                            //获取领导批示列表
                            BLL.LeadInstruct leadInstructBLL = new BLL.LeadInstruct();
                            string strWhere = "FDocId=" + documentModel.FDocId + " and a.FEntityNo='" + GlobalConstant.ENTITYNO + "'";
                            DataSet dslt = leadInstructBLL.GetList(strWhere);
                            ViewData["leadInstruct"] = dslt;

                        }

                        ViewData["FIsExamine"] = docClsModel.FIsExamine != "Y" ? "N" : "Y";

                        //处理图片
                        string pattern1 = "width\\s?=\\s?\"(\\d+)\"\\s+height\\s?=\\s?\"(\\d+)";
                        string pattern2 = "width\\s?:\\s?(\\d+)px;\\s+height\\s?:\\s?(\\d+)px";
                        int matchType = 0;
                        //利用正则替换内容模块
                        MatchCollection tdMatchs = Regex.Matches(documentModel.FContentTxt,
                        @"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>",
                        RegexOptions.IgnoreCase | RegexOptions.Multiline);

                        for (int i = tdMatchs.Count - 1; i >= 0; i--)
                        {
                            string oldimgUrl = tdMatchs[i].Value;
                            MatchCollection tdMatchsTmp = Regex.Matches(oldimgUrl,
                        pattern1, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                            if (tdMatchsTmp.Count == 0)
                            {
                                tdMatchsTmp = Regex.Matches(oldimgUrl,
                       pattern2, RegexOptions.IgnoreCase | RegexOptions.Multiline);
                                matchType = 2;
                            }
                            else
                            {
                                matchType = 1;
                            }
                            if (tdMatchsTmp.Count > 0)
                            {

                                string imgSizeValue = tdMatchsTmp[0].Value;
                                string width = tdMatchsTmp[0].Groups[1].Value; //宽    
                                string height = tdMatchsTmp[0].Groups[2].Value; //高 
                                int _width = 0;
                                int _height = 0;
                                int newWidth = 0;
                                int newHeight = 0;
                                if (int.TryParse(width, out _width) && int.TryParse(height, out _height))
                                {
                                    if (_width > GlobalConstant.IMG_SHOW_MAXWIDTH)
                                    {
                                        newWidth = GlobalConstant.IMG_SHOW_MAXWIDTH;
                                        newHeight = (_height * GlobalConstant.IMG_SHOW_MAXWIDTH) / _width;
                                        string newImgUrl = "";
                                        if (matchType == 1)
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width='" + newWidth + "' height='" + newHeight + "'");
                                        }
                                        else
                                        {
                                            newImgUrl = oldimgUrl.Replace(imgSizeValue, "width:" + newWidth + "px; height:" + newHeight + "px");
                                        }
                                        documentModel.FContentTxt = documentModel.FContentTxt.Replace(oldimgUrl, newImgUrl);
                                    }
                                }

                            }
                        }


                        //获取此文档被引用的栏目
                        BLL.DocRefImp docRefImp = new BLL.DocRefImp();
                        List<Model.DocRefImp> docRefImpList = docRefImp.GetListByDocId(GlobalConstant.ENTITYNO, docId);
                        string docRefImpClsName = "";
                        if (docRefImpList.Count > 0)
                        {
                            List<CommonValueModel> commValueList = new List<CommonValueModel>();
                            foreach (Model.DocRefImp docRefImpModel in docRefImpList)
                            {
                                commValueList.Add(new CommonValueModel { Text = docRefImpModel.FDocClsName, Value = docRefImpModel.FDocClsCd });
                                docRefImpClsName += docRefImpModel.FDocClsName + ",";
                            }

                            if (docRefImpClsName != "")
                            {
                                docRefImpClsName = "此信息已被下列栏目引用：" + docRefImpClsName.Trim(',');
                            }

                            ViewData["docRefImpClsName"] = docRefImpClsName;
                            ViewData["docRefImpClsJson"] = JsonConvert.SerializeObject(commValueList);
                        }
                        else
                        {
                            ViewData["docRefImpClsName"] = "";
                            ViewData["docRefImpClsJson"] = "";
                        }

                        if (template != "")
                        {
                            ViewData["templateName"] = template;
                        }

                        if (viewName == "")
                        {
                            return View("DocView", documentModel);
                        }
                        else
                        {
                            return View(viewName, documentModel);
                        }
                    }

                }
                else
                {
                    Response.Write("<script>alert('对应信息类别不存在');window.close();</script>");
                    Response.Flush();
                    Response.End();
                    return null;
                }

            }
            else
            {
                Response.Write("<script>alert('信息不存在');window.close();</script>");
                Response.Flush();
                Response.End();
                return null;
            }
        }

        public string GetTemplTopPicPath(Model.DocCls docClsModel)
        {
            string imgPath = "";
            //获取最上级有模板顶部图片路径的栏目
            string ztzlDoc = System.Configuration.ConfigurationManager.AppSettings["doc_ztzl_cls"];
            if (docClsModel.FPreDocClsCd != ztzlDoc)
            {
                Model.DocCls tmpDocClsModel = new Model.DocCls();
                tmpDocClsModel = docClsBLL.GetModel(docClsModel.FEntityNo, docClsModel.FPreDocClsCd);
                while (tmpDocClsModel != null && !string.IsNullOrEmpty(tmpDocClsModel.FPreDocClsCd) && string.IsNullOrEmpty(tmpDocClsModel.FTemplTopPicPath))
                {
                    tmpDocClsModel = docClsBLL.GetModel(tmpDocClsModel.FEntityNo, tmpDocClsModel.FPreDocClsCd);
                }
                if (tmpDocClsModel != null)
                {
                    imgPath = tmpDocClsModel.FTemplTopPicPath;
                }
            }
            else
            {
                imgPath = docClsModel.FTemplTopPicPath;
            }
            return imgPath;
        }

    }
}

